package com.lei.zjs.service.ebo;

import java.util.List;

import javax.annotation.Resource;

import org.activiti.engine.ProcessEngine;
import org.activiti.engine.impl.persistence.entity.UserEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.lei.zjs.dao.RoleDao;
import com.lei.zjs.dao.UserDao;
import com.lei.zjs.service.ebi.UserService;
import com.lei.zjs.utils.MD5Utils;
import com.lei.zjs.vo.Role;
import com.lei.zjs.vo.User;

@Service
@Transactional
public class UserServiceImpl implements UserService{

	@Resource
	private UserDao userDao;
	@Resource
	private ProcessEngine processEngine;
	@Resource
	private RoleDao roleDao;

	@Override
	public User login(User model) {
		//对密码进行加密
		String password = MD5Utils.md5(model.getPassword());
		List<User> list = userDao.findByNamedQuery("findByUsernameAndPassword", model.getUsername(),password);
		if (list != null && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public void editPassword(String id, String password) {
		password = MD5Utils.md5(password);
		userDao.executeByNamedQuery("editPassword", password, id);
	}

	@Override
	public List<User> findAll() {
		return userDao.findAll();
	}

	@Override
	public void save(User user,String[] roleIds) {
		String password = user.getPassword();
		password = MD5Utils.md5(password);
		user.setPassword(password);
		userDao.save(user);
		org.activiti.engine.identity.User actUser = new UserEntity();
		actUser.setId(user.getId());
		processEngine.getIdentityService().saveUser(actUser );
		if (roleIds != null && roleIds.length >0) {
			for (String id : roleIds) {
				Role role = roleDao.findById(id);
				user.getRoles().add(role);
				processEngine.getIdentityService().createMembership(actUser.getId(), role.getName());
			}
		}
	}
	
}
